package com.highbury5.blog.util.redis;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class JedisClusterFactory {

    private static final Log log = LogFactory.getLog(JedisClusterFactory.class);

    private List<String> hostPortList;

    private int timeout;

    private JedisCluster jedisCluster;

    public void init(){
        Set<HostAndPort> nodes = new HashSet<>();
        for(String hostPort:hostPortList){
            String[] hostPortNode = hostPort.split(":");
            if(hostPortNode.length == 2){
                HostAndPort hostAndPort = new HostAndPort(hostPortNode[0],Integer.parseInt(hostPortNode[1]));
                nodes.add(hostAndPort);
            }
        }
        try {
            jedisCluster = new JedisCluster(nodes, timeout);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public void destroy(){
        if(jedisCluster != null) {
            try {
                jedisCluster.close();
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
    }

    public void setHostPortList(List<String> hostPortList) {
        this.hostPortList = hostPortList;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public JedisCluster getJedisCluster() {
        return jedisCluster;
    }
}
